
function GetLocationList(data)
{
    // data is in this format:  1,'TD1':2,'TD2'
    // so need to create chart xaxis from it by spliting it in two dimentional array
    var xaxisList = new Array(0);
    var temp;
    var index = 0;

    // JQuery Foreach loop
    $.each(data.split(":"), function() {        
        temp = this.split(",");        
        xaxisList[index++] = new Array(temp[0],temp[1]);
    });    
    return xaxisList;
}

function LocationToVerify(fishDetailList, fishName, locationID, startIndex)
{
    var _FLAG = false;
    var temp = "";

    // FishDetail Format: [LocID],[Fishname],[Quantity],[FishID]
    if(startIndex < (fishDetailList.length - 1)){
        for(var findex = (startIndex + 1); findex < fishDetailList.length; findex++){
            // If Next Location ID same then proceed otherwise skip as location ids are sorted so if different this means now this ID will not occur
            temp = fishDetailList[findex].split(",");            
            if(temp[0] == locationID){
                if(temp[1] == fishName){                    
                    _FLAG = true;
                    break;
                }
            }
            else
                break;
        }
    }

    return _FLAG;
}

function DrawChart(params,year_value)
{
var ul="";
    if (year_value==undefined)
        {
            ul="http://" + location.hostname + "/main/Chart_Data?search=" + params;
        }
    else
        {
             ul="http://" + location.hostname + "/main/Chart_Data?search=" + params+"DATE_FLAG"+year_value;
        }
    downloadUrl(url = ul, function(returnVal) {
    var plotarea = null;
       if(returnVal != "")
       {
            var rawData = returnVal.split("|");
            
            if(rawData.length == 5)
            {
                var xaxisList = GetLocationList(rawData[0]);

                // data is in this format:  1,'Fish1',1.00:2,'Fish2',2.00
                // so need to create chart xaxis from it by spliting it in two dimentional array
                var dataList = new Array(0);
                var temp;
                var temp2;
                var fishName = "";
                var fishID = "";
                var arrIndex = 0;
                var arrIndex2 = 0;
                var arrIndex3 = 0;
                var arrIndex4 = 0;
                var tempDataArray = new Array(0);
                var tempDataArray2 = new Array(0);
                var tempDataArray3 = new Array(0);

                var fishDetailList = rawData[1].split(":");
                
                for(var fishIndex = 0; fishIndex < fishDetailList.length; fishIndex++){
                    temp = fishDetailList[fishIndex].split(",");
                    if((temp[1] !=  fishName || fishName == "") && !containsObj(tempDataArray2, temp[3]))
                    {
                        fishName = temp[1];

                        for(var fishIndex2 = 0; fishIndex2 < fishDetailList.length; fishIndex2++){
                            temp2 = fishDetailList[fishIndex2].split(",");                            
                            
                            if(temp2[1] == fishName){                                
                                tempDataArray[arrIndex++] = new Array(temp2[0], parseInt( temp2[2]));
                                tempDataArray3[arrIndex4++] = temp2[0];
                            }
                            else
                            {
                                if(!containsObj(tempDataArray3, temp2[0]) && !LocationToVerify(fishDetailList, fishName, temp2[0], fishIndex2)){
                                        tempDataArray[arrIndex++] = new Array(temp2[0], 0);
                                        tempDataArray3[arrIndex4++] = temp2[0];
                                }
                            }
                        }
                        //alert(fishName + "--> " + tempDataArray);
                        dataList[arrIndex3++] = {label: fishName, data: tempDataArray.sort()};
                        tempDataArray2[arrIndex2++] = temp[3];// fishName ;

                        tempDataArray = new Array(0);    // Clearing array for next data
                        tempDataArray3 = new Array(0);    // Clearing array for next data
                        arrIndex = 0;               // Clearing array index for next data
                        arrIndex4 = 0;
                    }
                }
                
                // Clear Chart Legend
                document.getElementById("spUnitList").innerHTML = "";
                document.getElementById("spYearList").innerHTML = "";
                document.getElementById("spDepthList").innerHTML = "";

                // Add nodes in Chart Legend (unit)
                document.getElementById("spUnitList").appendChild(document.createTextNode(rawData[2]));

                // Add nodes in Chart Legend (unit)
                document.getElementById("spDepthList").appendChild(document.createTextNode(rawData[4]));

                var yearList = rawData[3].split(",");

                for(var idx = 0; idx < yearList.length; idx++)
                {
                    var link = document.createElement ('A');
                    link.appendChild (document.createTextNode (yearList[idx]));
                    link.setAttribute ('href', '#');
                    link.setAttribute ('onclick', "refreshChart('"+ yearList[idx] +"');");

                    // Add nodes in Chart Legend (Year)
                    document.getElementById("spYearList").appendChild(link);
                }                               

                var options = {                             
                             series: {
                                 stack: true,
                                 lines: {
                                     show: false,
                                     steps: false
                                 },
                                 bars: {
                                     show: true,
                                     lineWidth: 2, // in pixels 
                                     barWidth: 0.6,
                                     align: 'center',
//                                     fill: true,
//                                     fillColor: null,
                                     horizontal: false // when horizontal, left is now top
                                 },
                                 shadowSize: 3
                             },
                             grid: {
                backgroundColor: { colors: ["#fff", "#eee"]},
                canvasText: {show: true, font: "sans 8px"},
                labelMargin: 10
                                },
            
                             legend: {
                                 show: true,
                                 noColumns: 3,
//                                 labelFormatter: null, // fn: string -> string
//                               labelWidth: 30,
//                                 labelBoxBorderColor: "#ccc", // border color for the little label boxes
                                 position: "ne",
                                 container:document.getElementById("spFishList"),
                                 backgroundColor: null, // null means auto-detect                      
                                 backgroundOpacity: 0.85 // set to 0 to avoid background
                             },
                             selection: {mode: "x"},                             
//                             color: "rgb(30, 180, 20)",
                           xaxis: {ticks: xaxisList, autoscaleMargin: null},
                           yaxis: {labelWidth:25}
                    };

                    
                //document.getElementById("reportarea").style.width = 100 + "%";
                plotarea = $("#chart_canvas");
                
                $.plot( plotarea , dataList,options);

                // Hide No Data Available Message
                
                document.getElementById("hide_data").style.display = "block";
                
            }
        }
        else
        {
            var options_blank = {
                         series: {
                             stack: 0,
                             lines: {
                                 show: false,
                                 steps: false
                             },
                             bars: {
                                 show: true,
                                 lineWidth: 2, // in pixels
                                 barWidth: 0.6,
                                 align: 'left',
                                 fill: true,
                                 fillColor: null,
                                 horizontal: false // when horizontal, left is now top
                             },
                             shadowSize: 3
                         },
                         legend: {
                             show: true,
                             noColumns: 10000,
                             labelFormatter: null, // fn: string -> string
                             labelWidth: 30,
                             labelBoxBorderColor: "#ccc", // border color for the little label boxes
                             position: "ne",
                             margin: 5,
                             container: null,
                             backgroundColor: null, // null means auto-detect
                             backgroundOpacity: 0.85 // set to 0 to avoid background
                         },
                         selection: {mode: "x"},
                         color: "rgb(30, 180, 20)",
                         xaxis: {ticks: 0, autoscaleMargin: null},
                         grid: {hoverable: true, autoHighlight: true, aboveData: true},
                         zoom: {interactive: true},
                         pan: {interactive: true},
                         yaxis: {min: 0, tickDecimals: 0, overflow: scroll}
                };

                plotarea = $("#chart_canvas");
                $.plot( plotarea , new Array(0,0), options_blank );                 
                
                document.getElementById("hide_data").style.display = "none";
                document.getElementById("chart_canvas").innerHTML = "No Data Found";
                
                
        }
    });    
}

// Returns TRUE if Array contains the object otherwise returns FALSE
function containsObj(arr, obj) {
  var i = arr.length;
  while (i--) {
    if (arr[i] === obj) {
      return true;
    }
  }
  return false;
}

function handleResize() {
  return windowHeight() - document.getElementById('header').offsetHeight;
}

function windowHeight() {
  // Standard browsers (Mozilla, Safari, etc.)
  if (self.innerHeight)
    return self.innerHeight;
  // IE 6
  if (document.documentElement && document.documentElement.clientHeight)
    return document.documentElement.clientHeight;
  // IE 5
  if (document.body)
    return document.body.clientHeight;
  // Just in case.
  return 0;
}

$(document).ready(function(){
    $(".report-slide").click(function(){
        
            $("#reportarea").slideToggle("slow");
            $(this).toggleClass("active");

            if(document.getElementById("hfBtnChartStatus").value == "0")
            {
                document.getElementById("hfBtnChartStatus").value = 1;                
            }
            else if(document.getElementById("hfBtnChartStatus").value == "1")
            {
                document.getElementById("hfBtnChartStatus").value = 0;
            }
            if (Flag_Search_Panel_Status=="Search")
                {setFilter("2", "");}
            else if (Flag_Search_Panel_Status=="History")
                {setFilter_History("2", "");}
            
return false;
    });
});

//$(function() {
//        $( "#reportarea" ).accordion({
//        });
//});


function downloadUrl(url, callback) {
  var request = window.ActiveXObject ?
      new ActiveXObject('Microsoft.XMLHTTP') :
      new XMLHttpRequest;

  request.onreadystatechange = function() {
    if (request.readyState == 4) {
      request.onreadystatechange = doNothing;
      callback(request.responseText, request.status);
    }
  };

  request.open('GET', url, true);
  request.send(null);
}

function parseXml(str)
{
    if (window.ActiveXObject) {
        var doc = new ActiveXObject('Microsoft.XMLDOM');
        doc.loadXML(str);
        return doc;
    } else if (window.DOMParser) {
        return (new DOMParser).parseFromString(str, 'text/xml');
    }
}

// Set the Chart width to 100% when RightNav Collapsed
function EnlargeChart(dvChart, dvRightNavStatus)
{
    
    if( dvChart) {
        if( dvRightNavStatus == "0")
        {
            dvChart.style.width = 100 + "%";
            
        }
        else
            {
            dvChart.style.width = 60 + "%";
            }

        if(dvChart.style.display != ""){
             
        }

        if (Flag_Search_Panel_Status=="Search")
                {setFilter("2", "");}
            else if (Flag_Search_Panel_Status=="History")
                {setFilter_History("2", "");}

    }
}
function refreshChart(year_para)
{
    if (Flag_Search_Panel_Status=="Search")
                {setFilter("2","", year_para);}
            else if (Flag_Search_Panel_Status=="History")
                {setFilter_History("2","", year_para);}
    
}
function SaveSearchData()
{

    var para="";
    if (Flag_Search_Panel_Status=="Search")
                {
                   para= setFilter("2","", "",true);}
            else if (Flag_Search_Panel_Status=="History")
                {para=setFilter_History("2","","",true);}
                if (para!="")
                    {
                        window.open("http://127.0.0.1/searchresult/ExcelData/search/"+para);
                        
                        }
    
}

function saveFlotGraphAsPNG(placeholderID, targetID) {

          var divobj = document.getElementById(placeholderID);

          var oImg = Canvas2Image.saveAsPNG(divobj.childNodes[0], true);

          if (!oImg) {
              alert("Sorry, this browser is not capable of saving PNG files!");
              return false;
          }

          oImg.id = "canvasimage";

            saveImageAs(oImg);
//          document.getElementById(targetID).removeChild(document.getElementById(targetID).childNodes[0]);
//          document.getElementById(targetID).appendChild(oImg);
          

        }
